var express = require('express');
var app = express();
var co = require('co')


app.get('/status', require('express-status-monitor')())

//var devServer = require('./public/wexin-orders/build/dev-server');
//devServer.init(app);
var {
	StoreNedb
} = require("./src/services/businessNedb");
var compression = require('compression')
app.use(compression())

var path = require('path');
var hbs = require('hbs');
var config = require('./config');
var qs = require('querystring');
app.use(express.query());

app.all('*', function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
	res.header('Access-Control-Allow-Headers',
		'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
	);
	res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
	if (req.method == 'OPTIONS') {
		res.send(200);
	} else {
		next();
	}
});

app.use(require('compression')({
	threshold: 512
}));

//var bodyParser = require('body-parser');
//app.use(bodyParser.json());

// use cookie and sessio
//app.use(express.cookieParser());
app.use(require('express-session')({
	secret: "sessio@n key must b3e a sec!ret",
	saveUninitialized: true,
	resave: true,
	// set session timeout
	cookie: {
		path: '/',
		httpOnly: true,
		maxAge: 60 * 60 * 1000
	}
}));
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
	extended: false
}));
app.use(bodyParser.json());

//app.all(/\/stores\/.*\/member\/.*/, require('./src/controllers/memberController').filter);
//app.param('storeId',require('./src/controllers/storeController').loadStoreParam);

//微信MP API routes
var wcmpApiRoutes = require('./src/wechat/common/routes');
var routes = require('./src/common/routes');
var dispatcher = require('./dispatcher');
dispatcher.dispatch(app, routes.concat(wcmpApiRoutes));

app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.set("views", __dirname + "/src/views");
hbs.registerPartials(__dirname + '/src/views/partials');

require('./src/common/mpj-modules').registerHelpers(hbs);

app.use("/mstores/:storeId/ordering/:tableId", function(req, res) {
	console.log("mstores/:storeId/ordering/:tableId");
	res.redirect('/t/' + req.params.tableId);
})
app.use("/", function(req, res, next) {
	next()
})

//微信授权
// MP_verify_Eec2PsowP4JjQVKt
app.get('/MP_verify_*.txt', function (req, res) {
  res.send(req.params[0]);
});

app.use("/s/:storeId/n/:numberPlate", function(req, res) {
	console.log("s/:storeId/ordering/:numberPlate");
	co(function*() {
		var storeInfo = yield StoreNedb.getWechatInfo(req.params.storeId);
		var o = {
			model: 2,
			v: config.app.wexinOrderVersion,
			storeId: req.params.storeId,
			numberPlate: req.params.numberPlate
		}
		res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
			storeInfo.appid +
			'&redirect_uri=' + config.app.mstoreUrl +
			'/t/jump.html&response_type=code&scope=snsapi_base&state=' +
			JSON.stringify(o) + '#wechat_redirect'
		);
	})
})
app.use("/s/:storeId/", function(req, res) {
	// try {
	//
	// } catch (e) {
	//
	// }
	console.log("s/:storeId/", req.params.storeId);
	co(function*() {
		var storeInfo = yield StoreNedb.getWechatInfo(req.params.storeId);
		var o = {
			model: 2,
			v: config.app.wexinOrderVersion,
			storeId: req.params.storeId
		}
		res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
			storeInfo.appid +
			'&redirect_uri=' + config.app.mstoreUrl +
			'/t/jump.html&response_type=code&scope=snsapi_base&state=' +
			JSON.stringify(o) + '#wechat_redirect'
		);
	})
})
app.get('/mstores/*', function(request, response, next) {
	var url = request.url.replace(/^\/mstores\/[^\/]+/, '');
	// url = url.split('?')[0];
	request.url = url;
	console.log(url)
	next();

	//response.sendFile(path.join(__dirname, 'public') + url);
});

app.use(express.static(path.join(__dirname, 'public')));

var wechat = require('./src/wechat');
//公众平台机器人
app.use('/wechat/mp/robot', wechat.wcmp.robot);


app.set('port', process.env.PORT || 9200);
if ('test' == app.get('env')) {
	app.set('port', process.env.test_port || 8081);
}
require('./src/api')(app).then(function(serverCreated) {
	app.use(express.static(path.join(__dirname, 'dist'), {
		maxAge: 86400000
	}));
	var server = app.listen(app.get('port'), function() {
		console.log("mSite listening on port %d in %s mode", server.address().port,
			app.settings.env);
	});
	return serverCreated(server);
});
